package testJdk.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author keyer
 * @Description : 实现一个简单的服务器，用telnet测试
 * Created by cyd on 2021-04-28 16:29:19
 */
public class TestSocket {
    public static void main(String[] args) {
        try {
            // 建立套接字
            ServerSocket serverSocket = new ServerSocket(8189);
            offerServer(serverSocket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于关闭连接，并重新监听
     * @throws IOException
     */
    private static void offerServer(ServerSocket serverSocket) throws IOException {
        // 监听端口获得连接对象
        Socket incoming = serverSocket.accept();
        // 从连接对象获得输入流与输出流
        InputStream inputStream = incoming.getInputStream();
        OutputStream outputStream = incoming.getOutputStream();

        // 获取输入和输出流
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream, true);

        // 向客户端输出文字
        out.println("Hello! Enter bye to shoutdown the server!");
        boolean done = false;

        // 死循环提供服务
        while (!done && in.hasNextLine()) {
            String line = in.nextLine();
            out.println();
            out.println("Echo:" + line);
            if (line.trim().equals("bye")) {
                done = true;
            }
        }
        // 关闭连接
        incoming.close();
        //从新开启服务
        offerServer(serverSocket);
    }
}
